package com.sisyphus.spinach.ui.configs.impl;

import android.content.Context;


import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.sisyphus.spinach.core.INetPageTask;
import com.sisyphus.spinach.network.view.Info;
import com.sisyphus.spinach.network.view.SmartRefreshList;
import com.sisyphus.spinach.ui.NetTaskRefreshLoadMore;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.RecyclerView;

public abstract class DefaultPageTemplate<T> implements IPageTemplate<T> {

    protected final RecyclerView       mRecyclerView;
    protected final SmartRefreshLayout mRefreshLayout;

    public DefaultPageTemplate(RecyclerView recyclerView, SmartRefreshLayout refreshLayout) {
        mRecyclerView = recyclerView;
        mRefreshLayout = refreshLayout;
    }

    public Context getContext() {
        return mRecyclerView.getContext();
    }

    @Override
    public void execute(@NonNull Lifecycle lifecycle) {
        mRecyclerView.setAdapter(adapter(mRecyclerView)); // 获取列表adapter
        INetPageTask.Presenter<T, INetPageTask.View<T>> presenter = presenter(); // 获取分页网络任务
        presenter.bind(view()); // 获取view
        lifecycle.addObserver(presenter);

        // 绑定监听
        mRefreshLayout.setOnRefreshLoadMoreListener(new NetTaskRefreshLoadMore<>(presenter));

        // 自动请求
        mRefreshLayout.autoRefresh();
    }

    @Override
    public INetPageTask.View<T> view() {
        return new SmartRefreshList<>(mRecyclerView, mRefreshLayout, new Info<>(getContext()));
    }

    public abstract BaseQuickAdapter<T, BaseViewHolder> adapter(RecyclerView recyclerView);

}
